import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:hitutor/UI/Home/OrderClass/OrderClass2.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/Step.dart';

import '../../Member/FavoriteTeacher/TeacherInfo.dart';
import 'TeacherInfo.dart';

class ClassBody extends StatefulWidget {
  Function() onToCalendar;

  ClassBody({Key? key, required this.onToCalendar}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ClassBodyState();
  }
}

class ClassBodyState extends State<ClassBody> {
  ///課程
  dynamic chooseLesson;
  List<dynamic> LessonList = [];

  ChooseClass() {
    showWheelDialog2(context, "", LessonList, "displayLessonName", (int index) {
      chooseLesson = LessonList[index];
      setState(() {});
    });
  }

  ///日期
  DateTime startDate = DateTime.now();
  DateTime endDate = DateTime.now().add(Duration(days: 7));

  ChooseStartDate() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日",
        //通过空格设置滚轮数量
        minDateTime: DateTime.now(),
        maxDateTime: DateTime.now().add(Duration(days: 35)),
        initialDateTime: DateTime(startDate.year, startDate.month, startDate.day),
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (endDate.isBefore(dateTime)) {
        showToast("開始日期不能晚於結束日期");
        return;
      }
      startDate = dateTime;
      setState(() {});
    });
  }

  ChooseEndDate() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日",
        //通过空格设置滚轮数量
        minDateTime: DateTime.now(),
        maxDateTime: DateTime.now().add(Duration(days: 35)),
        initialDateTime: DateTime(endDate.year, endDate.month, endDate.day),
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (dateTime.isBefore(startDate)) {
        showToast("開始日期不能晚於結束日期");
        return;
      }

      endDate = dateTime;
      setState(() {});
    });
  }

  ///時間
  DateTime startTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 0, 0);
  DateTime endTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 59);

  ChooseStartTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "HH時 mm分", //通过空格设置滚轮数量
        minuteDivider: 30,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (endTime.isBefore(dateTime)) {
        showToast("開始時間不能晚於結束時間");
        return;
      }
      startTime = dateTime;
      setState(() {});
    });
  }

  ChooseEndTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "HH時 mm分", //通过空格设置滚轮数量
        minuteDivider: 30,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (dateTime.isBefore(startTime)) {
        showToast("開始時間不能晚於結束時間");
        return;
      }
      endTime = dateTime;
      setState(() {});
    });
  }

  ///教學平台
  String platform = "";
  int platformCode = 0;
  List<dynamic> platformList = [];

  ChoosePlatform() {
    showWheelDialog2(context, "", platformList, "plateformName", (int index) {
      platform = platformList[index]["plateformName"];
      platformCode = platformList[index]["plateformCode"];
      setState(() {});
    });
  }

  getData() {
    HttpGo(context).get("/Lesson/HitutorAPPBookingInfo?studentId=${Global.studentId}", {}, (data) {
      LessonList = data["lessonList"];
      platformList = data["plateformList"];
    }, (code, error) => showToast(error));
  }

  ///授課老師 - 來源
  List<String> teacherSourceList = ["全部（All）", "我的最愛（My Favorite）", "歷史名單（Historical List）"];
  String teacherSource = "全部（All）";
  bool selectAllTeacher = true;

  ChooseSource() {
    showWheelDialog(context, "", teacherSourceList, (int index) {
      teacherSource = teacherSourceList[index];
      selectAllTeacher = index == 0;
      if (selectAllTeacher) {
        chooseTeacher = null;
      }
      setState(() {});
    });
  }

  ///授課老師
  dynamic chooseTeacher;

  List<dynamic> TeacherList = [];

  ChooseTeacher() {
    if (teacherSource == teacherSourceList[1]) {
      getTeacher("GetFavoriteTeacherList");
    } else if (teacherSource == teacherSourceList[2]) {
      getTeacher("GetHistoryTeacherList");
    }
  }

  getTeacher(String api) {
    if (chooseLesson == null) {
      return;
    }
    HttpGo(context).post("/Teacher/$api", {
      "studentId": Global.studentId,
      "lessonId": chooseLesson["lessonId"],
      "plateformCode": platformCode,
    }, (data) {
      TeacherList = data["teacherList"];
      showWheelDialog2(context, "", TeacherList, "teacherName", (int index) {
        chooseTeacher = TeacherList[index];
        setState(() {});
      });
    }, (code, error) => showToast(error));
  }

  ///下一步
  nextClick() {
    if (chooseLesson == null) {
      showToast("請選擇您要訂課的課程");
      return;
    }
    if (!selectAllTeacher && chooseTeacher == null) {
      showToast("請選擇授課老師");
      return;
    }
    Map<String, dynamic> params = {
      "studentId": Global.studentId,
      "lessonId": chooseLesson["lessonId"],
      "purchaseOrderId": chooseLesson["purchaseOrderId"],
      "beginDate": getStrTime(startDate, DateUtil.YMD),
      "endDate": getStrTime(endDate, DateUtil.YMD),
      "beginTime": getStrTime(startTime, DateUtil.HM),
      "endTime": getStrTime(endTime, DateUtil.HM),
      "teacherIdList": selectAllTeacher ? null : [chooseTeacher["teacherId"]], //無語，要傳數組
      "plateformCode": platformCode,
      "timeZone": DateTime.now().timeZoneOffset.inMinutes,
    };
    HttpGo(context).post("/Lesson/HitutorAPPGetCanBookList", params, (data) {
      PageUtil().open(
          context,
          OrderClass2(
            chooseTeacher,
            TeacherList: TeacherList,
            bookInfoList: data["bookInfoList"],
            params: params,
            onNext: widget.onToCalendar,
          ));
    }, (code, error) => showToast(error));
  }

  getTeacherInfo(var teacherId) {
    HttpGo(context).get("/Teacher/GetTeacherIntro?teacherId=$teacherId", {}, (data) {
      showWidgetDialog(context, TeacherInfo(data));
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      SingleChildScrollView(
          padding: EdgeInsets.fromLTRB(16, 24, 16, 32),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text("請選擇您要訂課的課程", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
            ChooserBox(chooseLesson == null ? "" : chooseLesson["displayLessonName"],
                margin: EdgeInsets.fromLTRB(0, 8, 0, 8), onTap: ChooseClass),
            chooseLesson == null
                ? Container()
                : Container(
                    decoration: Global.getWhiteBg_shadow(6, MyColor.EE),
                    width: double.infinity,
                    padding: EdgeInsets.all(8),
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 16),
                    child: Text(
                      "課堂時間：${chooseLesson["lessonTime"]}分鐘課程\n師資群：${chooseLesson["teacherNntionality"]}\n剩餘堂數/課程總覽：${chooseLesson["remainingLessonCount"]} / ${chooseLesson["allLessonCount"]}",
                      style: TextStyle(fontSize: 13, height: 1.5, color: MyColor.Orange, fontWeight: FontWeight.bold),
                    )),
            Text("請選擇您要訂課的日期", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
            Padding(
                padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
                child: Row(children: [
                  Expanded(child: ChooserBox(getStrTime(startDate, DateUtil.YMD), onTap: ChooseStartDate)),
                  Text("　~　"),
                  Expanded(child: ChooserBox(getStrTime(endDate, DateUtil.YMD), onTap: ChooseEndDate)),
                ])),
            Text("請選擇您要訂課的時段", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
            Padding(
                padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
                child: Row(children: [
                  Expanded(child: ChooserBox(getStrTime(startTime, DateUtil.HM), onTap: ChooseStartTime)),
                  Text("　~　"),
                  Expanded(child: ChooserBox(getStrTime(endTime, DateUtil.HM), onTap: ChooseEndTime)),
                ])),
            Text("請選擇授課方式", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
            ChooserBox(platform, margin: EdgeInsets.fromLTRB(0, 8, 0, 8), onTap: ChoosePlatform),
            Text("請選擇授課老師", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
            ChooserBox(teacherSource, margin: EdgeInsets.fromLTRB(0, 8, 0, 8), onTap: ChooseSource),
            Visibility(
                visible: !selectAllTeacher,
                child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text("請選擇要訂課的老師", style: TextStyle(fontSize: 13, color: MyColor.Blue, fontWeight: FontWeight.bold)),
                  ChooserBox(chooseTeacher == null ? "" : chooseTeacher["teacherName"],
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 8), onTap: ChooseTeacher),
                  TeacherIntro(onTap: () {
                    getTeacherInfo(chooseTeacher["teacherId"]);
                  })
                ])),
          ])),
      Container(alignment: Alignment.bottomRight, margin: EdgeInsets.all(16), child: NextStep(onTap: nextClick))
    ]);
  }
}

class TeacherIntro extends StatelessWidget {
  Function()? onTap;

  TeacherIntro({this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: onTap,
        child: Container(
            decoration: BoxDecoration(
                color: MyColor.BlueHome,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(2),
                  topRight: Radius.circular(14),
                  bottomLeft: Radius.circular(2),
                  bottomRight: Radius.circular(14),
                )),
            padding: EdgeInsets.only(left: 4),
            height: 26,
            width: 100,
            child: Row(children: [
              Text("教師簡介", style: TextStyle(fontSize: 13, color: MyColor.EE)),
              LocalImage("search.png", width: 28, height: 12)
            ])));
  }
}
